package aggregation

import (
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	statistics "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/aggregation"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/aggregation"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type StatisticsController struct {
	controller.BaseController
	statisticsService aggregation.StatisticsServiceIface
}

func NewStatisticsController(statisticsService aggregation.StatisticsServiceIface) *StatisticsController {
	return &StatisticsController{
		statisticsService: statisticsService,
	}
}

// RegisterRouter
// 注册路由
func (c *StatisticsController) RegisterRouter(g *gin.RouterGroup) {
	// 应用排名列表
	g.GET("statistics/use-rank-list", c.useRankList)
	// 统计数据
	g.POST("statistics/data", c.Data)
}

func (c *StatisticsController) Data(ctx *gin.Context) {
	req := &statistics.DataParam{}
	if err := ctx.ShouldBind(req); err != nil {
		stark.Logger.Infof(ctx, "DataParam-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	data, err := c.statisticsService.Data(ctx, req)
	if err != nil {
		stark.Logger.Infof(ctx, "Data-err: %+v, req: %+v", err, req)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, data)
}

func (c *StatisticsController) useRankList(ctx *gin.Context) {
	req := &statistics.UseRankListParam{}
	if err := ctx.ShouldBind(req); err != nil {
		stark.Logger.Infof(ctx, "UseRankList-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(req, err))
		return
	}

	useRankListData, err := c.statisticsService.UseRankList(ctx, req)
	if err != nil {
		stark.Logger.Infof(ctx, "UseRankList-err: %+v, req: %+v", err, req)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, useRankListData)
}
